#!/bin/sh

PWD=`pwd`
App=`find ./ -name bdp-oss*-SNAPSHOT.jar`
RESOURCE_NAME=$PWD/$App
PORT=20004

profile=""
if [ -n "$1" ];then
  profile="-Dspring.profiles.active=$1"
fi
echo $profile $RESOURCE_NAME

Stop(){
  # check the number of application
  cnt=`ps -ef|grep $App|grep -v grep|grep -v kill|awk '{print $2}'| wc -l`
  if (( $cnt > 1 )); then
    echo "Error! Too many $App runs, count:$cnt"
    exit
  fi

  # stop process
  tpid=`ps -ef|grep $App|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'stop process...'
    kill -15 $tpid
  fi
  sleep 5

  # kill process
  tpid=`ps -ef|grep $App|grep -v grep|grep -v kill|awk '{print $2}'`
  if [ ${tpid} ]; then
    echo 'kill process!'
    kill -9 $tpid
    tpid=`ps -ef|grep $App|grep -v grep|grep -v kill|awk '{print $2}'`
    if [ ${tpid} ]; then
        echo 'stop fail! $App is already running.'
        exit -1
    else
        echo 'stop success! $App is NOT running.'
    fi
  else
    echo 'stop success!'
  fi

  rm -f tpid
}

Start(){
  cmd="java -jar -Dloader.path=. -Dfile.encoding=utf-8 $profile $RESOURCE_NAME"
  echo "$cmd"
  nohup $cmd >/dev/null 2>&1 &
  echo $! > tpid

  cnt=`ps -ef|grep $App|grep -v grep|grep -v kill|awk '{print $2}'| wc -l`
  if (( $cnt != 1 )); then
    echo "$App start fail!"
  else
    echo "sleep up to 40 seconds to wait for the application to start up"
    for (( i=0; i< 8; i++ )); do
      sleep 5
      cnt=`lsof -i:$PORT | grep -v COMMAND | wc -l`
      if (( $cnt == 1 )); then
        echo "$App start success!"
        ps -ef|grep $App|grep -v grep|grep -v kill
        exit 0
      fi
    done
    echo "$App start fail!"
  fi
}

Stop

Start
